package com.hou.netty.udp.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

//udp数据格式
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    //udp通道只有一个,关闭了就不能接受了
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        String req = datagramPacket.content().toString(CharsetUtil.UTF_8);
        System.out.println(req);
        //向客户端发送消息,构建udp消息对象     通过Packet中的sender获取发送消息客户端的ip和端口号
        DatagramPacket dp = new DatagramPacket(Unpooled.copiedBuffer("我收到了你的消息".getBytes()), datagramPacket.sender());
        channelHandlerContext.channel().writeAndFlush(dp);
    }
}
